/**
 * @filename:SysFileController 2022年1月27日
 * @project Wonder xhadmin Framework  V1.0
 * Copyright(c) 2020 LuZhongren Co. Ltd. 
 * All right reserved. 
 */
package com.wonder.admin.controller;


import com.wonder.admin.domain.SysFile;
import com.wonder.admin.service.SysFileService;
import com.wonder.admin.request.SysFileRequest;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wonder.common.common.AjaxResult;
import com.wonder.common.common.CommonPage;
import com.wonder.common.config.WonderConfig;
import com.wonder.common.utils.MessageUtils;
import com.wonder.common.utils.StringUtils;
import com.wonder.common.utils.file.FileUploadUtils;
import com.wonder.common.utils.file.FileUtils;
import com.wonder.common.utils.file.MimeTypeUtils;
import com.wonder.common.utils.file.OSSServiceUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**   
 * 
 * <p>说明： 文件管理API接口层</P>
 * @version: V1.0
 * @author: LuZhongren
 * @time    2022年1月27日
 *
 */
@Api(tags = "图片文件管理")
@RestController
@RequestMapping("/admin")
public class SysFileController {
	
	private static final Logger log = LoggerFactory.getLogger(SysFileController.class);
	
	@Autowired
	private SysFileService sysFileService;
	
	@Autowired
	OSSServiceUtil ossServiceUtil;
	
	@ApiOperation(value = "图片文件管理列表")
	@RequestMapping(value = "/Base/fileList", method = RequestMethod.POST)
	public AjaxResult<CommonPage<SysFile>> index(@RequestBody SysFileRequest sysFileRequest) {
	
		Page<SysFile> page = new Page<SysFile>(sysFileRequest.getPage(), sysFileRequest.getLimit());
		IPage<SysFile> list = sysFileService.selectList(sysFileRequest, page);
		return AjaxResult.success(CommonPage.restPage(list));
	}
	
	/**
	 * @explain 添加
	 * @param   对象参数：SysFile
	 * @return  Boolean
	 * @author  Wonder
	 */
	@PostMapping("/add")
	@ApiOperation(value = "添加文件", notes = "作者：Wonder")
	public AjaxResult<SysFile> add(@RequestBody SysFile entity){

		if (null!=entity) {
		    String validate=sysFileService.validate(entity);
		    if(StringUtils.hasText(validate))
		         return AjaxResult.failed(validate);
			boolean rsg = sysFileService.save(entity);
			if (rsg) {
				  return AjaxResult.success(MessageUtils.message("insert.success"));
			  }else {
				  return AjaxResult.failed(MessageUtils.message("insert.fail"));
			  }
		}else {
			return AjaxResult.failed(MessageUtils.message("insert.parameter.error"));
		}
	}
	
	/**
	 * @explain 查询对象  <swagger GET请求>
	 * @param   对象参数：id
	 * @return  JsonResult
	 * @author  Wonder
	 */
	@PostMapping("/getUpdateInfo")
	@ApiOperation(value = "获取文件对象", notes = "作者：Wonder")
	public AjaxResult<SysFile> getUpdateInfo(@RequestBody Map<String,Object> map){
	    if(map==null) AjaxResult.failed(MessageUtils.message("input.parameter.error"));
		Long info_id=Long.parseLong(map.get("info_id").toString());
	    
		SysFile logininfor=sysFileService.getById(info_id);
		
		if (null!=logininfor ) {
			 return AjaxResult.success(logininfor);
		}else {
			 return AjaxResult.failed(MessageUtils.message("search.not.exist"));
		}
		
	}
	
	/**
	 * @explain 修改
	 * @param   对象参数：SysFile
	 * @return  Boolean
	 * @author  Wonder
	 */
	@PostMapping("/update")
	@ApiOperation(value = "修改", notes = "作者：Wonder")
	public AjaxResult<SysFile> update(@RequestBody SysFile entity){
		if (null!=entity) {
		    String validate=sysFileService.validate(entity);
		    if(StringUtils.hasText(validate))
		         return AjaxResult.failed(validate);
			boolean rsg = sysFileService.updateById(entity);
			if (rsg) {
				  return AjaxResult.success(MessageUtils.message("update.success"));
			  }else {
				  return AjaxResult.failed(MessageUtils.message("update.fail"));
			  }
		}else {
			return AjaxResult.failed(MessageUtils.message("update.not.exist"));
		}
	}
	
	/**
	 * @explain 删除文件
	 * @param   对象参数：id
	 * @return  JsonResult
	 * @author  Wonder
	 */
	@PostMapping("/delete")
	@ApiOperation(value = "删除", notes = "作者：Wonder")
	public AjaxResult<SysFile> delete(@RequestBody Map<String,Object> map){
		if(map==null)return AjaxResult.failed(MessageUtils.message("search.not.exist"));
		String ids=map.get("info_id").toString();
		String[] deleteIds=StringUtils.split(ids, ',');
		List<Long> idList=new ArrayList<>(); 
		for(int i=0;i<deleteIds.length;i++)
		{
			idList.add( Long.parseLong(deleteIds[i]));//整数数组
		}

	    boolean rsg = sysFileService.removeBatchByIds(idList);
	    if (rsg) {
		    return AjaxResult.success(MessageUtils.message("delete.success"));
	    }else {
		   return AjaxResult.failed(MessageUtils.message("delete.fail"));
	    }
		
	}
	
	/**
	 * @explain 删除图片
	 * @param   对象参数：Filepath
	 * @return  JsonResult
	 * @author  Wonder
	 */
	@PostMapping("/Base/deleteFile")
	@ApiOperation(value = "根据文件路径删除图片文件", notes = "作者：Wonder")
	public AjaxResult<SysFile> deleteFile(@RequestBody Map<String,Object> map){
		if(map==null)return AjaxResult.failed(MessageUtils.message("search.not.exist"));
		List<String> filepaths=StringUtils.castList(map.get("filepath"),String.class);
		if(filepaths==null || filepaths.size()==0)AjaxResult.failed(MessageUtils.message("search.not.exist"));
	
	    boolean rsg = sysFileService.remove(new QueryWrapper<SysFile>().in("filepath", filepaths));
	    if (rsg) {
		    return AjaxResult.success(MessageUtils.message("delete.success"));
	    }else {
		   return AjaxResult.failed(MessageUtils.message("delete.fail"));
	    }
		
	}
	

	
	 /**
     * 通用下载请求
     * 
     * @param fileName 文件名称
     * @param delete 是否删除
     */

    @ApiOperation(value = "文件下载")
    @GetMapping("common/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request)
    {
        try
        {
            if (!FileUtils.isValidFilename(fileName))
            {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = WonderConfig.getDownloadPath() + fileName;

            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, realFileName));
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete)
            {
                FileUtils.deleteFile(filePath);
            }
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 通用上传请求
     */
    @ApiOperation(value = "通用文件上传")
    @PostMapping("/file/upload")
    public AjaxResult<String> uploadFile(@RequestPart MultipartFile file) throws Exception
    {
        try
        {
        	 if (!file.isEmpty())
             {  
        		 String fileType=file.getContentType();
        		 String hd5="";
        		 //Check the file hash, if the same file existed, then return the file path.
        		 if(Arrays.asList(MimeTypeUtils.DEFAULT_ALLOWED_IMAGES).contains(fileType)) {
        		 hd5=FileUtils.getMd5(file);
        		 SysFile existedFile=sysFileService.getOne(new QueryWrapper<SysFile>().eq("hash", hd5));
        		 if(existedFile!=null) return AjaxResult.data(existedFile.getFilepath());
        		 }
        		 String imgUrl="";
        		 switch(WonderConfig.getUploadType()){
        		 case "ali":
        			 imgUrl = ossServiceUtil.uploadAliyun(file); 
        			 break;
        		 default:
        	            // 上传并返回新文件名称
        			 imgUrl= FileUploadUtils.upload( file);
        	             	          
        		 }
        		 
        		 if(Arrays.asList(MimeTypeUtils.DEFAULT_ALLOWED_IMAGES).contains(fileType)) {
			    		 SysFile newFile=new SysFile();
			    		 newFile.setFilepath(imgUrl).setHash(FileUtils.getMd5(file));
			    		 sysFileService.save(newFile);
        		 }
 
                 return AjaxResult.data(imgUrl);
             }
             return AjaxResult.failed("上传图片异常，请联系管理员");
        }
        catch (Exception e)
        {
            return AjaxResult.failed(e.getMessage());
        }
    }
    
    /**
     * 通用上传请求
     */
    @ApiOperation(value = "文件上传")
    @PostMapping("/Upload/upload")
    public AjaxResult<String> uploadFile(MultipartFile file,String upload_config_id) throws Exception
    {
        try
        {
        	 if (!file.isEmpty())
             {  
        		 String fileType=file.getContentType();
        		 String hd5="";
        		 //Check the file hash, if the same file existed, then return the file path.
        		 if(Arrays.asList(MimeTypeUtils.DEFAULT_ALLOWED_IMAGES).contains(fileType)) {
        		 hd5=FileUtils.getMd5(file);
        		 SysFile existedFile=sysFileService.getOne(new QueryWrapper<SysFile>().eq("hash", hd5));
        		 if(existedFile!=null) return AjaxResult.data(existedFile.getFilepath());
        		 }
        		 
        		 String imgUrl="";
        		 switch(WonderConfig.getUploadType()){
        		 case "ali":
        			 imgUrl = ossServiceUtil.uploadAliyun(file); 
        			 break;
        		 default:
        	            // 上传并返回新文件名称
        			 imgUrl= FileUploadUtils.upload( file);
        	             	          
        		 }
        		 
        		 if(Arrays.asList(MimeTypeUtils.DEFAULT_ALLOWED_IMAGES).contains(fileType)) {
			    		 SysFile newFile=new SysFile();
			    		 newFile.setFilepath(imgUrl).setHash(hd5);
			    		 sysFileService.save(newFile);
        		 }
 
                 return AjaxResult.data(imgUrl);
             }
             return AjaxResult.failed("上传图片异常，请联系管理员");
        }
        catch (Exception e)
        {
            return AjaxResult.failed(e.getMessage());
        }
    }
	
	
}